package com.tools.payhelper.nxes;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tools.payhelper.AlipayHook;
import com.tools.payhelper.utils.DateUtils;
import com.tools.payhelper.utils.JSONParser;
import com.tools.payhelper.utils.LogUtil;
import com.tools.payhelper.utils.PayHelperUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;

/**
 * TODO:
 *
 * @author hm
 * @date 2019/2/19
 * @copyright
 */
public class NXESHook {
    public static String BILLRECEIVED_ACTION = "com.tools.payhelper.billreceived";
    private static String apiorder_id = null;
    private static String money = null;
    private static String lastId = null;

    static Object objectDetailList = null;

    public static void hook(final ClassLoader classLoader, final Context context) {

        XposedHelpers.findAndHookMethod("com.buybal.buybalpay.base.BaseFragmentActivity", classLoader,
                "onCreate", Bundle.class, new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        if (param.thisObject.getClass().getName().equals("com.buybal.buybalpay.activity.ReciveAmtActivity")) {
                            apiorder_id = ((Activity) param.thisObject).getIntent().getStringExtra("apiorder_id");
                            money = ((Activity) param.thisObject).getIntent().getStringExtra("money");
                            EditText c = (EditText) XposedHelpers.getObjectField(param.thisObject, "c");
                            c.setText(money);

                            int j = XposedHelpers.getIntField(param.thisObject, "j");
                            XposedHelpers.setObjectField(param.thisObject, "j", 1);
//                            View onclickView = ((Activity) param.thisObject).findViewById(2131165406);
                            View onclickView = (View) XposedHelpers.getObjectField(param.thisObject, "g");

                            onclickView.performClick();
                            try {
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {

                                            XposedHelpers.callMethod(param.thisObject, "finish");
                                        } catch (Exception localException) {
                                            XposedBridge.log("关闭失败：" + localException.getMessage());
                                        }
                                    }
                                }, (long) (Math.random() * 1800 % 600 + 1.5 * 1000));

                            } catch (Exception e) {
                                e.printStackTrace();
                                LogUtil.printLog("关闭失败：" + e);
                            }

                        } else if (param.thisObject.getClass().getName().equals("com.buybal.buybalpay.activity.ScanPayActivity")) {
                            XposedHelpers.callMethod(param.thisObject, "finish");

                        } else if (param.thisObject.getClass().getName().equals("com.buybal.buybalpay.activity.TradeResultActivity")) {
                            XposedHelpers.callMethod(param.thisObject, "finish");
                        }
                    }
                });

        //监控语音播报的 不灵,是用轮训账单方式
        XposedHelpers.findAndHookMethod("com.baidu.tts.control.MySyntherizer", classLoader,
                "speak", String.class, new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
//                        String speakStr = (String) param.args[0];
                        //农信易扫收款0.56元
                        /*String amount = StringUtils.getTextCenter(speakStr, "收款", "元");
                        Intent broadCastIntent = new Intent();
                        broadCastIntent.putExtra("bill_no", "");
                        broadCastIntent.putExtra("bill_money", amount + "");
                        broadCastIntent.putExtra("payWay", "wechat");
                        broadCastIntent.putExtra("bill_type", "nxes");
                        broadCastIntent.setAction(AlipayHook.BILLRECEIVED_ACTION);
                        context.sendBroadcast(broadCastIntent);*/


//                        LogUtil.printLog("speak----->p0=" + param.args[0]);
                    }
                });


        XposedHelpers.findAndHookMethod("com.buybal.buybalpay.bean.ResponseparamsQrlink", classLoader,
                "getCodeUrl", new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        LogUtil.printLog("getCodeUrl----->" + param.getResult());

                        Intent broadCastIntent = new Intent();
                        broadCastIntent.putExtra("type", "nxes");
                        broadCastIntent.putExtra("payurl", (String) param.getResult());
                        broadCastIntent.putExtra("money", money);
                        broadCastIntent.putExtra("apiorder_id", apiorder_id);

                        broadCastIntent.setAction(AlipayHook.QRCODERECEIVED_ACTION);
                        context.sendBroadcast(broadCastIntent);


                    }
                });


        XposedHelpers.findAndHookMethod("com.buybal.buybalpay.activity.ReciveAmtActivity", classLoader, "onClick", View.class,
                new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        int j = XposedHelpers.getIntField(param.thisObject, "j");
                        LogUtil.printLog("onClick----->j:" + j);
                        int s = XposedHelpers.getIntField(param.thisObject, "s");
                        LogUtil.printLog("onClick----->s:" + s);

                        String n = (String) XposedHelpers.getObjectField(param.thisObject, "n");
                        String p = (String) XposedHelpers.getObjectField(param.thisObject, "p");
                        String q = (String) XposedHelpers.getObjectField(param.thisObject, "q");

                        LogUtil.printLog("onClick----->n:" + n);
                        LogUtil.printLog("onClick----->p:" + p);
                        LogUtil.printLog("onClick----->q:" + q);


                        EditText c = (EditText) XposedHelpers.getObjectField(param.thisObject, "c");

                        LogUtil.printLog("onClick----->c str:" + c.getText().toString());

                        TextView f = (TextView) XposedHelpers.getObjectField(param.thisObject, "f");
                        LogUtil.printLog("onClick----->f:" + f.getText().toString());
                        TextView i = (TextView) XposedHelpers.getObjectField(param.thisObject, "i");
                        LogUtil.printLog("onClick----->k:" + i.getText().toString());
                        TextView m = (TextView) XposedHelpers.getObjectField(param.thisObject, "m");
                        LogUtil.printLog("onClick----->m:" + m.getText().toString());
                        LogUtil.printLog("id----->view:" + ((View) param.args[0]).getId());

                        Activity activity = (Activity) param.thisObject;
                        int activitys = PayHelperUtils.isActivityTop(activity);
//                        if (activitys > 2) {
//                            activity.finish();
//                        }

                    }
                }
        );


        try {

            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.activity.DetailStoreListActivity", classLoader, "initData", new XC_MethodHook() {
                @Override
                public void afterHookedMethod(MethodHookParam param) throws Throwable {
                    try {
                        objectDetailList = param.thisObject;
                        LogUtil.printLog("#####", "农信获取成功");
                        Toast.makeText(context
                                , "农信易扫_获取成功", Toast.LENGTH_LONG).show();

                        PayHelperUtils.sendLoginId("ooxx", "nxys", context);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            XposedHelpers.findAndHookMethod("com.buybal.buybalpay.net.okhttputil.OkhttpNetHandler", classLoader, "onHttpSuccess", Message.class, new XC_MethodHook() {
                @Override
                public void afterHookedMethod(MethodHookParam param) throws Throwable {
                    try {
                        Message msg = (Message) param.args[0];
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        LogUtil.printLog("#####", "NetHandler 获取到的结果 》》》》》》》》》》》》onsuccesss_jsonobject:" + jsonObject.toString());
                        //判断是否有
                        if (jsonObject.has("orderList")) {//判断是否有订单
                            LogUtil.printLog("#####", "NetHandler 订单:" + jsonObject.toString());
                            String orderList = jsonObject.getString("orderList");
                            JSONArray jsonArray = new JSONArray(orderList);
                            if (jsonArray == null || jsonArray.length() <= 0) {
                                return;
                            }
                            String stringJsonarray = jsonArray.toString();
                            if (stringJsonarray.contains("amount")
                                    && stringJsonarray.contains("orderTime")
                                    && stringJsonarray.contains("orderId")) {

                                List<NxOrder> nxList = new ArrayList<>();
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject01 = jsonArray.getJSONObject(i);
                                    NxOrder bean = new NxOrder();
                                    if (jsonObject01.has("amount")) {
                                        bean.setAmount(jsonObject01.getString("amount") + "");
                                    }
                                    if (jsonObject01.has("orderTime")) {
                                        bean.setOrderTime(jsonObject01.getString("orderTime") + "");
                                    }
                                    if (jsonObject01.has("orderId")) {
                                        bean.setOrderId(jsonObject01.getString("orderId") + "");
                                    }
                                    bean.setStatus("0");
                                    nxList.add(bean);
                                }
                                if (nxList == null || nxList.size() <= 0) {
                                    return;
                                }
                                LogUtil.printLog("#####", "bean List:" + JSONParser.toString(nxList));

//
                                Intent intent2 = new Intent();
                                intent2.putExtra("list", JSONParser.toString(nxList));
                                intent2.setAction("com.tools.payhelper.nx.getbill");
                                context.sendBroadcast(intent2);


                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    //刷新网页请求
    public static void startListResbonse() {
        try {
            if (objectDetailList != null) {
                String stringDate = DateUtils.getCurrentDate();
                XposedHelpers.callMethod(objectDetailList, "searchDayStoreNet", stringDate, "1", "15");
            } else {
                LogUtil.printLog("#####", "对象空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

